
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -<
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	
	public function Welcome(){
		parent::__construct();
		//si el usuario ya se encuentra loggeado
		$this->load->helper("url");
		//if($this->session->userdata('logged_in') == TRUE){
		//	redirect("/dispatcher/plotLayout");
		//}
		
		$this->load->helpers(array('form','asset','language','url','html'));
		$this->load->model('usuario_model','usuarioDB');
		if($this->session->userdata('language') == ''){
			$this->session->set_userdata('language','spanish');
		}
		$this->lang->load("login_layout",$this->session->userdata('language'));
	}
	
	public function index()
	{
		//salvando la página actual
		//$this->session->set_userdata("current_page",$this->uri->uri_string());
		
		$data['title'] = "Welcome - Login";
		$data['extraCss'][] = array();	
		$data['extraCss'][] = array("source" => "stylesheet.css", "module" => "login_modal");
		$data['extraCss'][] = array("source" => "basic.css", "module" => "login_modal");
		$data['includes'] = array();
		$data['includes'][] = array("source" => "jquery-1.6.1.min.js", "module" => '');
		$data['includes'][] = array("source"=>"jquery.simplemodal.js", "module" => "login_modal");
		$data['includes'][] = array("source" => "init.js", "module" => "login_modal");
		 
		$this->load->view('header',$data);
		$data['ERROR'] = $this->lang->line('error_failed');
		$data['content'] = $this->load->view('logo_amplio',null,true);
		 
		$this->load->view('content',$data);
		$this->load->view('footer');
		//insertamos el simple modal login	
		$data['destination'] = "/welcome/validLogin";
		$this->load->view('login_layout',$data);
	
	}
	
	
	public function validLogin(){
		
		if($this->input->post('Login') ){
			$username = $this->input->post('user',true);
			$password = $this->input->post('password',true);
			$result = $this->usuarioDB->valida_usuario($username,$password);
			
			if($result){
				$this->_setSessionVars($username);
				redirect("/dispatcher/plotLayout");
			}else{
				$this->session->set_flashdata('errorMessage',$this->lang->line('error_failed'));
				redirect("/welcome/","refresh");
			}
			
		}else{
			$this->session->set_flashdata('errorMessage',$this->lang->line('error_no_form'));
			redirect("/welcome/","refresh");
		}
			
	}
	
	/*
	 * Public authentication method for Android apps
	 * @params 
	 *		username
	 *		password
	 * @return
	 * 		$response -	tipo (String) en formato json con:
	 * 						 la respuesta a la petición de autenticación valid(boolean),
	 * 						 	
	 * 							
	 */
	
	public function validaLoginAndroid($username,$password)
	{
		
	
		$result = $this->usuarioDB->valida_usuario($username,$password);
		
		$response = array();
		if($result){
			$response["valid"] = "true";
			
			$user_array = $this->usuarioDB->get_usuario_by_username($username);
			$user_obj = $user_array[0];
			$database_array = $this->usuarioDB->get_database( $user_obj->dbid );
			$database_obj = $database_array[0];
			
			$response["dbname"] = $database_obj->dbname;
			$response["username"] = $user_obj->username;
		}else{
			$response["valid"] = "false";
		}
		
		echo json_encode($response);
		
	}
	

	private function _setSessionVars($username){
		
		$user_array = $this->usuarioDB->get_usuario_by_username($username);
		$user_obj = $user_array[0];
		
		//obteniendo la base de datos relacionada con el cliente
		$database_array = $this->usuarioDB->get_database( $user_obj->dbid );
		$database_obj = $database_array[0];
		$newdata = array(
						'logged_in' => true,
						'username' => $user_obj->username,
						'id' => $user_obj->id,
						'dbid' => $user_obj->dbid,
						'dbname' => $database_obj->dbname,
						'mysqlPass' => $database_obj->dbpassword);
		$this->session->set_userdata($newdata);
	
		
		return $user_obj;
	}
	
	public function setLanguage($language){
		//$language = $this->input->get('lang',true);
		$this->session->set_userdata('language',$language);
		//redirect($this->session->userdata('current_page'));
		header('location:'.$_SERVER['HTTP_REFERER']);
	}
	
	public function logout(){
		$this->session->sess_destroy();
		redirect('/');
	}
	
	
	//Android methods
	private function _MySQLDateOffset($dt,$year_offset='',$month_offset='',$day_offset='')
	{
		  return ($dt=='0000-00-00') ? '' :
	      date ("Y-m-d", mktime(0,0,0,substr($dt,5,2)+$month_offset,substr($dt,8,2)+$day_offset,substr($dt,0,4)+$year_offset));
	}
	
	public function get_interval_android($db,$variable,$year,$month,$date,$numDias){
// 		http://megan.teksar.com.mx/DBXTra/index.php/welcome/get_interval_android/selder/Humidity_1/2010/2/14/7
		
		//conexión a la base de datos correspondiente
		$config['hostname'] = "localhost";
		$config['username'] = "root";
		$config['password'] = "Android123";
		$config['database'] = $db;
		$config['dbdriver'] = "mysql";
		$config['dbprefix'] = "";
		$config['pconnect'] = FALSE;
		$config['db_debug'] = TRUE;
		$this->load->model('dbclient_model','dbclient',$config);
		
		$query = "Select Date_Format(tkm_log.fecha, '%Y-%m-%d') AS fecha, ROUND(Avg(tkm_log.$variable), 2) As average 
From tkm_log, (Select Date_Format(Concat(tkm_year.tkyears, '-', tkm_month.tkmonths, '-', tkm_day.tkdays), '%y-%m-%d') As fechaparametro From tkm_month, tkm_year, tkm_day Where tkm_year.tkyears = $year And tkm_month.tkmonths = $month And tkm_day.tkdays = $date) GetDateParameter,
 (Select tkm_intervalo.tknumdays As numDias From tkm_intervalo Where tkm_intervalo.tknumdays = $numDias) getIntervalo 

Where tkm_log.fecha Between date_sub(Cast(GetDateParameter.fechaparametro As DateTime), Interval getIntervalo.numDias Day) AND Cast(GetDateParameter.fechaparametro As DateTime)
Group By Date(tkm_log.fecha) 
Order By tkm_log.fecha"; 
	
		
		$Set = $this->dbclient->db->query($query);
		$resultSet = $Set->result();
		echo json_encode($resultSet);
	
	}
	
	
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */